package com.sxpi.zixun.controller.upload;

import com.sxpi.zixun.common.enums.AdminErrorResultEnum;
import com.sxpi.zixun.common.ex.PugValidatorException;
import com.sxpi.zixun.controller.BaseController;
import com.sxpi.zixun.pojo.Resources;
import com.sxpi.zixun.service.resources.IResourcesService;
import com.sxpi.zixun.service.upload.OssUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @Author: 董伟豪
 * @Date: 2022/9/5 9:52
 */
@RestController
public class OssController extends BaseController {

    @Autowired
    private OssUploadService ossUploadService;

    @Autowired
    private IResourcesService resourcesService;

    @PostMapping("/upload/oss/file")
    public Map<String,Object> fileUpload2(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {

        if (file.isEmpty()) {
            return null;
        }

        if(file.getSize() > 1024 * 1024 * 2){
            throw new PugValidatorException(AdminErrorResultEnum.FILE_UPLOAD_LIMIT_ERROR);
        }

        if(!file.getContentType().equalsIgnoreCase("image/png") &&
                !file.getContentType().equalsIgnoreCase("image/jpg") &&
                !file.getContentType().equalsIgnoreCase("image/jpeg")){
            throw new PugValidatorException(AdminErrorResultEnum.FILE_UPLOAD_TYPE_ERROR);
        }

        String dir = request.getParameter("dir");
        if(StringUtils.isEmpty(dir)){
            dir = "course";
        }

        // handler调用文件上传的service 得到文件的虚拟路径
        Map<String,Object> map = ossUploadService.uploadfile(file,dir);
        // 资源入库 设计模式--- 观察设计模式
        String cid = request.getParameter("cid");
        Resources resources = new Resources();
        resources.setFilename(String.valueOf(map.get("filename")));
        resources.setNewname(String.valueOf(map.get("newname")));
        resources.setStatus(1);
        resources.setIsdelete(0);
        resources.setResourceId(new Long(cid));
        resources.setType(1);
        resources.setFilesize(String.valueOf(map.get("size")));
        resources.setExt(String.valueOf(map.get("ext")));
        resources.setPath(String.valueOf(map.get("url")));
        resources.setDownpath(String.valueOf(map.get("url")));
        resources.setIspublic(1);
        resourcesService.saveOrUpdate(resources);
        // 返回资源ID
        map.put("resources",resources);
        return map;
    }
}
